'use strict';
const uniID = require('uni-id-common');

exports.main = async (event, context) => {
  let body = event;
  if (event.body !== undefined) {
    body = JSON.parse(event.body);
  }

  const uniIDIns = uniID.createInstance({ context });
  const db = uniCloud.database();
  const _ = db.command;

  try {
    // 1. 身份验证
    const { uid } = await uniIDIns.checkToken(body.uniIdToken);
    if (!uid) {
      return { code: 403, msg: '身份验证失败' };
    }

    const { consultantId, rating } = body;
    if (typeof rating === 'undefined' || rating === null) {
      return { code: 400, msg: '缺少必要参数：rating' };
    }
    
    if (!Number.isInteger(rating) || rating < 1 || rating > 5) {
      return { code: 400, msg: '评分必须是 1 到 5 的整数' };
    }

    // 是否需要更新评分
    let shouldUpdateConsultantRating = false;

    // 2. 查询 appoint_schedule 中是否有预约记录
    const appointRes = await db.collection('appoint_schedule')
      .where({ consultant: consultantId, uid })
      .get();

    if (appointRes.data.length > 0) {
      const { day, appointedSlot } = appointRes.data[0];

      const recordRes = await db.collection('appoint_records')
        .where({ consultant: consultantId, user: uid, day, appointedSlot })
        .get();

      if (recordRes.data.length > 0) {
        await db.collection('appoint_records').doc(recordRes.data[0]._id).update({
          rating,
          update_time: new Date()
        });
      } else {
        await db.collection('appoint_records').add({
          consultant: consultantId,
          user: uid,
          day,
          appointedSlot,
          rating,
          created_at: Date.now(),
          update_time: new Date()
        });
      }

      shouldUpdateConsultantRating = true;

    } else {
      // 无预约记录
      const latestRecordRes = await db.collection('appoint_records')
        .where({ consultant: consultantId, user: uid })
        .orderBy('created_at', 'desc')
        .limit(1)
        .get();

      if (latestRecordRes.data.length > 0) {
        await db.collection('appoint_records').doc(latestRecordRes.data[0]._id).update({
          rating,
          update_time: new Date()
        });
        shouldUpdateConsultantRating = true;
      } else {
        return { code: 404, msg: '没有预约记录，也没有评分记录，无法更新' };
      }
    }

    // ========== 新增：更新 consultants 表评分数据 ==========
    if (shouldUpdateConsultantRating) {
      await updateConsultantRating(db, consultantId,rating);
    }

    return { code: 0, msg: '评分已提交并更新' };

  } catch (e) {
    return { code: 500, msg: '服务器错误', error: e.message };
  }
};

// 更新 consultants 表评分数据
async function updateConsultantRating(db, consultantId, newRating) {
  const _ = db.command;

  // 获取平台总评分和评分数（用于贝叶斯平均）
	const platformAgg = await db.collection('consultants')
	  .aggregate()
	  .group({
		_id: null,
		totalScoreSum: { $sum: '$total_score' },
		scoreCountSum: { $sum: '$score_count' }
	  })
	  .end();
  console.log(platformAgg)
  const platformData = platformAgg.data[0] || {};
  const platformTotal = platformData.totalScoreSum || 0;
  const platformCount = platformData.scoreCountSum || 0;
  const C = platformCount > 0 ? platformTotal / platformCount : 4.2;

  const m = 10; // 贝叶斯平滑因子

  // 获取咨询师当前数据（可能字段不存在）
  const consultantRes = await db.collection('consultants')
    .where({ user_id: consultantId })
    .limit(1)
    .get();

  if (consultantRes.data.length === 0) return; // 咨询师不存在

  const consultant = consultantRes.data[0];
  const oldTotal = consultant.total_score || 0;
  const oldCount = consultant.score_count || 0;

  const newTotal = oldTotal + newRating;
  const newCount = oldCount + 1;

  const bayesianScore = (m * C + newTotal) / (m + newCount);

  // 更新 consultants 表
  await db.collection('consultants')
    .doc(consultant._id)
    .update({
      total_score: newTotal,
      score_count: newCount,
      rating: Math.round(bayesianScore * 100) / 100
    });
}
